<?php

namespace Modules\Api\Service;

use HiCommon\Repository\AgreementCateRepository;
use HiCommon\Repository\AgreementRepository;
use HiCommon\Repository\CollectRepository;
use HiCommon\Repository\HandbookRepository;
use HiCommon\Repository\ProtocolRepository;
use HiCommon\Repository\DiscoverRepository;
use HiCommon\Repository\DiscoverAppriseRepository;
use HiCommon\Repository\DiscoverZanRepository;
use HiCommon\Repository\UsersRepository;
use HiCommon\Repository\UserInviteRepository;
use Modules\Admin\Service\AppService;

class H5Service
{
    /**
     * 分享有礼
     * @param $uid
     * @return array
     */
    public function share($uid)
    {
        try {
            $url = env('API_HOST') . '/share-register?uid=' . $uid;
            $shareData = [
                "title" => '分享有礼',
                "content" => '推荐有礼，分享就有优惠，快来一起参与吧！',
                "url" => $url
            ];
            $data['uid'] = $uid;
            $data['url'] = $url;
            $data['shareInfo'] = json_encode($shareData, JSON_UNESCAPED_UNICODE);

            return hello_success('成功', $data);
        } catch (\Exception $exception) {
            return hello_error('失败', '', $exception->getMessage());
        }
    }

    /**
     * 分享有礼
     * @param $uid
     * @return array
     */
    public function my_invite($uid)
    {
        try {
            $arr_option['with'] = ['getToUser'];
            $arr_option['where'] = ['user_id' => $uid];
            $arr_option['field'] = ['id', 'user_id', 'to_user_id', 'created_at'];
            $result = UserInviteRepository::base_get_all($arr_option)->toArray();
            $list = [];
            foreach ($result as $item) {
                if ($item['get_to_user']) {
                    $img = $item['get_to_user']['head_img']['full_src'];
                    $list[] = [
                        'head_img' => $img ? $img : '/pages/imgs/you/you4.png',
                        'name' => $item['get_to_user']['nickname'] ?? $item['get_to_user']['username'],
                        'phone' => $item['get_to_user']['phone'],
                        'created_at' => $item['created_at']
                    ];
                }
            }

            return $list;
        } catch (\Exception $exception) {
            return hello_error('失败', '', $exception->getMessage());
        }
    }

    /**
     * 分享下载APP
     * @return array
     */
    public function share_app()
    {
        try {
            return AppService::get_new_version_list();
        } catch (\Exception $exception) {
            return hello_error('失败', '', $exception->getMessage());
        }
    }

    /*门店加盟*/
    public function help_shop_join()
    {

        $type = 3;//门店加盟
        $arr_option['field'] = ['title', 'content'];
        $arr_option['where'] = ['type' => $type, 'status' => 1];
        $arr_option['order'] = ['key' => 'sort', 'value' => 'asc'];
        $data = ProtocolRepository::get_all($arr_option)->toArray();
        if ($data) {
            return hello_success('成功！', $data);
        }
        return hello_error('暂无数据');
    }

    /**
     * 客服服务->帮助中心
     * @return array
     */
    public function help_center()
    {
        $arr_option = [
            'with' => ['question_list'],
            'order' => ['key' => 'sort', 'value' => 'asc']
        ];
        $result = AgreementCateRepository::base_get_all($arr_option)->toarray();

        if(count($result) <= 0){
            $arr_data = [
              'id'=>-1,
              'type'=>1,
              'title'=>'平台未添加帮助模块',
              'question_list'=>[]
            ];
            $result = [];
            $result[] = $arr_data;
        }
        return hello_success('成功', $result);
    }

    public function help_center_detail($n_id)
    {
        $n_id = intval($n_id);
        if ($n_id <= 0) {
            return hello_error('数据id不能为空');
        }

        $result = AgreementRepository::base_find_one($n_id);
        if (is_null($result)) {
            $arr_data = [];
        } else {
            $arr_data = $result->toarray();

        }
        return hello_success('成功！', $arr_data);
    }

    /**
     * 保养手册
     * @return array
     */
    public function handbook()
    {
        try {
            $arr_option = [
                'order' => ['key' => 'km', 'value' => 'asc'],
                'with' => ['get_handbook_upkeep_type']
            ];
            $data = HandbookRepository::base_get_all($arr_option)->toArray();

            $list = [];
            foreach ($data as $key => $vale) {
                $list[$key]['km'] = $vale['km'];
                $list[$key]['month'] = $vale['month'];
                $list[$key]['hand'] = array_column($vale['get_handbook_upkeep_type'], 'get_upkeep_type');
            }

            return hello_success('成功', $list);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 资讯详情
     * @param $id
     * @param $uid
     * @return array
     */
    public function news($id, $uid)
    {
        try {
            if ($id == 0) {
                die('参数错误！');
            }
            $arr_option['with'] = ['user', 'shop_user', 'zan', 'is_collect' => function ($query) use ($uid) {
                $query->where(['type' => 3, 'user_id' => $uid])->select(['id', 'x_id']);
            }];
            $arr_option['withCount'] = ['zan'];
            $data = DiscoverRepository::find_one($id, $arr_option);
            if ($data) {
                $info = $data->toArray();
                $zanUids = array_column($info['zan'], 'user_id');
                $info['zan'] = in_array($uid, $zanUids) ? 'zaned' : 'zan';
                $info['shop_user'] = $info['shop_user'] ?? ['username' => '信达养车'];
                $info['collect'] = count($info['is_collect']) > 0 ? 1 : 2;

                DiscoverRepository::increase_num($id, 'look_num');

                return hello_success('成功！', $info);
            }

            die('暂无数据！');
        } catch (\Exception $exception) {
            return hello_error('失败', '', $exception->getMessage());
        }
    }

    /**
     *  Ajax获取评论列表
     * @param $id
     * @param $page
     * @return array
     */
    public function comment($id, $uid, $page)
    {
        try {
            if ($id == 0 || $page == 0) {
                die('参数错误！');
            }

            $where = ['discover_id' => $id];
            $arr_option['with'] = ['to_user', 'zan_comment'];
            $arr_option['n_per_page'] = 10;

            $data = DiscoverAppriseRepository::get_list_by_where($where, $arr_option)->toArray();

            foreach ($data['data'] as $key => &$item) {
                $item['created_at'] = friendly_date(strtotime($item['created_at']));
                $item['zan_num'] = count($item['zan_comment']);
                $zanUids = array_column($item['zan_comment'], 'user_id');
                $item['zan'] = in_array($uid, $zanUids) ? 'zaned' : 'zan';

                $key = substr($item['user_id'], -1);

                if (empty($item['to_user'])) {
                    //游客默认头像
                    $item['to_user'] = [
                        "nickname" => '游客' . $item['user_id'],
                        "head_img" => [
                            "full_src" => "pages/imgs/you/you" . $key . ".png"
                        ]
                    ];
                }
            }

            $arr_data = [
                'total' => $data['total'],
                'page' => $data['to'],
                'data' => $data['data'],
            ];

            return hello_success('成功！', $arr_data);
        } catch (\Exception $exception) {
            return hello_error('失败', '', $exception->getMessage());
        }
    }

    /**
     * type(1评论资讯，2资讯点赞，3评论点赞，4删除评论，5收藏资讯)
     * @param $data
     * @return array
     */
    public function zan_comment_del($data)
    {
        try {
            if ($data['type'] == '1') {

                return self::addComment($data);

            } elseif ($data['type'] == '2') {

                return self::newsZan($data);

            } elseif ($data['type'] == '3') {

                return self::commentZan($data);

            } elseif ($data['type'] == '4') {

                return self::delComment($data);

            } elseif ($data['type'] == '5') {

                return self::newsCollect($data);

            } else {
                return hello_error('type参数错误！');
            }
        } catch (\Exception $exception) {
            return hello_error('失败', '', $exception->getMessage());
        }
    }

    /**
     * 评论资讯
     * @param $data
     * @return array
     */
    public function addComment($data)
    {
        if (empty($data['comment'])) {
            return hello_error('请输入评论内容！');
        }
        if (sensitive($data['comment'])) {
            return hello_error('敏感词汇禁止提交！');
        }

        $info = [
            'discover_id' => $data['id'],
            'user_id' => $data['uid'],
            'content' => htmlentities($data['comment'], ENT_COMPAT)
        ];
        $res = DiscoverAppriseRepository::base_add_one($info)->toArray();
        if ($res) {

            $result = self::getUserInfo($data['uid'], $res);

            return hello_success('评论成功！', $result);
        }

        return hello_error('评论失败！');
    }

    /**
     * 资讯点赞取消点赞
     * @param $data
     * @return array
     */
    public function newsZan($data)
    {
        $map = ['link_id' => $data['id'], 'user_id' => $data['uid'], 'type' => 1];
        if ($data['zan'] == 'zan') {
            $res = DiscoverZanRepository::base_add_one($map)->toArray();
        } else {
            $res = DiscoverZanRepository::base_delete_by_where($map, true);
        }
        if ($res) {
            return hello_success('成功！');
        }

        return hello_error('失败！');
    }

    /**
     * 删除评论
     * @param $data
     * @return array
     */
    public function delComment($data)
    {
        if (empty($data['cmid'])) {
            return hello_error('参数错误！');
        }

        $map = ['id' => $data['cmid'], 'user_id' => $data['uid']];
        $res = DiscoverAppriseRepository::base_delete_by_where($map, true);

        $map2 = ['link_id' => $data['cmid'], 'user_id' => $data['uid'], 'type' => 2];
        DiscoverZanRepository::base_delete_by_where($map2, true);

        if ($res) {
            return hello_success('删除成功！');
        }
        return hello_error('失败！');
    }

    /**
     * 点赞取消点赞
     * @param $data
     * @return array
     */
    public function commentZan($data)
    {
        $map = ['link_id' => $data['cmid'], 'user_id' => $data['uid'], 'type' => 2];
        if ($data['zan'] == 'zan') {
            $res = DiscoverZanRepository::base_add_one($map)->toArray();
        } else {
            $res = DiscoverZanRepository::base_delete_by_where($map, true);
        }
        if ($res) {
            return hello_success('成功！');
        }

        return hello_error('失败！');
    }

    public function newsCollect($data)
    {
        $arrInput = [
            'x_id' => $data['id'],
            'user_id' => $data['uid'],
            'type' => 3
        ];

        if ($data['state'] == 1) {//取消收藏
            if (CollectRepository::delete_one_to_where($arrInput)) {
                return hello_success('取消收藏！');
            }
        } else {
            if (CollectRepository::add_one($arrInput)) {
                return hello_success('收藏成功！');
            }
        }

        return hello_error('收藏失败！');
    }

    /**
     * 拼接评论内容
     * @param $uid
     * @param array $comm
     * @return string
     */
    public function getUserInfo($uid, $comm = [])
    {
        $arr_option['field'] = ['id', 'nickname', 'head_img'];
        $user = UsersRepository::get_one($uid, $arr_option);

        if ($user->first()) {
            $user = $user->toArray();
        } else {
            $key = array_rand([1, 2, 3, 4, 5, 6]);
            //游客默认头像
            $user = [
                "nickname" => '游客' . $comm['user_id'],
                "head_img" => [
                    "full_src" => "pages/imgs/you/you" . $key . ".png"
                ]
            ];
        }

        $html = ' <div class="cont">
                  <div class="img">
                     <img src="' . $user['head_img']['full_src'] . '" alt="">
                  </div>
                  <div class="text">
                      <p class="tit">
                          <span class="name">' . $user['nickname'] . '</span>
                          <span class="data">
                              <button type="button" data-id="' . $comm['id'] . '" zan="zan" class="layui-btn layui-btn-primary layui-btn-sm zanIng">
                                  <i class="layui-icon" style="margin-right: 0px;">&#xe6c6;</i>
                                  <span>0</span>
                              </button>
                          </span>
                      </p>
                      <p class="ct" style="-webkit-line-clamp: 3;">' . $comm['content'] . '</p>
                      <p style="margin-top: 5px;">
                          <span class="left">刚刚</span>
                          <button class="layui-btn layui-btn-primary layui-btn-sm delIng right" data-id="' . $comm['id'] . '">删除</button>
                      </p>
                  </div>
               </div>';

        return $html;
    }

}